package naga.x.platform2.channel.meitu.support;

import java.util.Map;
import java.util.Map.Entry;
import java.util.TreeMap;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSONObject;

import naga.x.platform2.channel.s399.support.S399Api;
import naga.x.platform2.utils.CommonUtils;
import naga.x.platform2.utils.IOUtils;

@Component
public class MeiTuApi {

	public static final String PROTOCOL_LOGIN = "100108";
	public static final String PROTOCOL_PAY = "100601";
	public static final String PROTOCOL_ORDER_QUERY = "100604";
	
	@Autowired
	private MeiTuConfig config;
	
	public String makeSign(Map<String, String> map) {
		StringBuilder builder = new StringBuilder();
		if (!(map instanceof TreeMap)) {
			map = new TreeMap<String, String>(map);
		}
		for (Entry<String, String> entry : map.entrySet()) {
			String key = entry.getKey();
			String value = CommonUtils.decodeURL(entry.getValue(), IOUtils.UTF8);
			builder.append(key).append('=').append(value).append('&');
		}
		builder.setLength(builder.length() - 1); // delete the last '&'
		builder.append(config.getSecretKey());
		return CommonUtils.md5(builder.toString());
	}
	
	public static Object newError(S399Api.Code code) {
		return newError(code.code, code.msg);
	}
	
	public static Object newError(int code, String msg) {
		JSONObject error = new JSONObject(2, true);
		error.put("code", code);
		error.put("msg", msg);
		return error;
	}
	
	public Object newOrder(String token) {
		JSONObject res = new JSONObject(2, true);
		res.put("code", S399Api.Code.SUCC.code);
		res.put("token", token);
		Map<String, String> map = new TreeMap<String, String>();
		map.put("token", token);
		res.put("sign", makeSign(map));
		return res;
	}
	
}
